<template>
  <div class="student-statistics">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span class="title">学生统计</span>
          <div class="header-actions">
            <el-button @click="refreshData">
              <el-icon><Refresh /></el-icon>
              刷新数据
            </el-button>
            <el-button @click="exportReport">
              <el-icon><Download /></el-icon>
              导出报告
            </el-button>
          </div>
        </div>
      </template>

      <!-- 统计卡片 -->
      <el-row :gutter="16" class="stats-row">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon total">
                <el-icon><User /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.total_students || 0 }}</div>
                <div class="stat-title">学生总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon active">
                <el-icon><UserFilled /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ getActiveStudents() }}</div>
                <div class="stat-title">在校学生</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon graduated">
                <el-icon><Trophy /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ getGraduatedStudents() }}</div>
                <div class="stat-title">已毕业</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon employment">
                <el-icon><Briefcase /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.employment_rate || 0 }}%</div>
                <div class="stat-title">就业率</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <el-row :gutter="16" class="charts-row">
        <!-- 学校分布 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span class="chart-title">学校分布</span>
            </template>
            <div ref="schoolChartRef" class="chart-container"></div>
          </el-card>
        </el-col>

        <!-- 专业分布 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span class="chart-title">专业分布</span>
            </template>
            <div ref="majorChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="16" class="charts-row">
        <!-- 年级分布 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span class="chart-title">年级分布</span>
            </template>
            <div ref="gradeChartRef" class="chart-container"></div>
          </el-card>
        </el-col>

        <!-- 性别分布 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span class="chart-title">性别分布</span>
            </template>
            <div ref="genderChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="16" class="charts-row">
        <!-- 学籍状态分布 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span class="chart-title">学籍状态分布</span>
            </template>
            <div ref="statusChartRef" class="chart-container"></div>
          </el-card>
        </el-col>

        <!-- 就业状态分布 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span class="chart-title">就业状态分布</span>
            </template>
            <div ref="employmentChartRef" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 入学趋势 -->
      <el-row :gutter="16" class="charts-row">
        <el-col :span="24">
          <el-card class="chart-card">
            <template #header>
              <span class="chart-title">最近入学趋势</span>
            </template>
            <div ref="enrollmentChartRef" class="chart-container-large"></div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Refresh, Download, User, UserFilled,
  Trophy, Briefcase
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { studentApi } from '@/api/students'

// 响应式数据
const loading = ref(false)
const statistics = reactive({
  total_students: 0,
  by_school: {},
  by_major: {},
  by_grade: {},
  by_status: {},
  by_employment_status: {},
  by_gender: {},
  recent_enrollments: [],
  employment_rate: 0
})

// 图表引用
const schoolChartRef = ref()
const majorChartRef = ref()
const gradeChartRef = ref()
const genderChartRef = ref()
const statusChartRef = ref()
const employmentChartRef = ref()
const enrollmentChartRef = ref()

// 图表实例
let schoolChart: echarts.ECharts | null = null
let majorChart: echarts.ECharts | null = null
let gradeChart: echarts.ECharts | null = null
let genderChart: echarts.ECharts | null = null
let statusChart: echarts.ECharts | null = null
let employmentChart: echarts.ECharts | null = null
let enrollmentChart: echarts.ECharts | null = null

// 方法
const fetchStatistics = async () => {
  loading.value = true
  try {
    const response = await studentApi.getStatistics()
    Object.assign(statistics, response.data)

    // 更新图表
    await nextTick()
    updateCharts()
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')

    // 使用模拟数据作为后备
    Object.assign(statistics, {
      total_students: 750,
      by_school: { '信息工程学院': 400, '机械工程学院': 350 },
      by_major: { '计算机科学与技术': 120, '软件工程': 95, '网络工程': 80, '信息安全': 65, '数据科学': 70 },
      by_grade: { '2021级': 150, '2022级': 180, '2023级': 200, '2024级': 220 },
      by_status: { 'active': 650, 'graduated': 100, 'suspended': 5, 'dropped': 2 },
      by_employment_status: { 'unemployed': 200, 'employed': 450, 'self_employed': 80, 'further_study': 20 },
      by_gender: { 'M': 420, 'F': 330 },
      recent_enrollments: [
        { enrollment_date: '2024-01', count: 20 },
        { enrollment_date: '2024-02', count: 15 },
        { enrollment_date: '2024-03', count: 25 },
        { enrollment_date: '2024-04', count: 30 },
        { enrollment_date: '2024-05', count: 35 },
        { enrollment_date: '2024-06', count: 40 },
        { enrollment_date: '2024-07', count: 45 }
      ],
      employment_rate: 85.5
    })

    await nextTick()
    updateCharts()
  } finally {
    loading.value = false
  }
}

const initCharts = () => {
  // 初始化所有图表
  schoolChart = echarts.init(schoolChartRef.value)
  majorChart = echarts.init(majorChartRef.value)
  gradeChart = echarts.init(gradeChartRef.value)
  genderChart = echarts.init(genderChartRef.value)
  statusChart = echarts.init(statusChartRef.value)
  employmentChart = echarts.init(employmentChartRef.value)
  enrollmentChart = echarts.init(enrollmentChartRef.value)

  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    schoolChart?.resize()
    majorChart?.resize()
    gradeChart?.resize()
    genderChart?.resize()
    statusChart?.resize()
    employmentChart?.resize()
    enrollmentChart?.resize()
  })
}

const updateCharts = () => {
  updateSchoolChart()
  updateMajorChart()
  updateGradeChart()
  updateGenderChart()
  updateStatusChart()
  updateEmploymentChart()
  updateEnrollmentChart()
}

const updateSchoolChart = () => {
  if (!schoolChart) return

  const data = Object.entries(statistics.by_school).map(([name, value]) => ({
    name,
    value
  }))

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '学校分布',
        type: 'pie',
        radius: '50%',
        data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  schoolChart.setOption(option)
}

const updateMajorChart = () => {
  if (!majorChart) return

  // 模拟专业数据
  const mockData = {
    '计算机科学与技术': 120,
    '软件工程': 95,
    '网络工程': 80,
    '信息安全': 65,
    '数据科学': 70
  }

  const data = Object.entries(mockData)
    .sort(([,a], [,b]) => b - a)
    .slice(0, 10)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'category',
      data: data.map(([name]) => name)
    },
    series: [
      {
        name: '学生数量',
        type: 'bar',
        data: data.map(([, value]) => value),
        itemStyle: {
          color: '#5470c6'
        }
      }
    ]
  }

  majorChart.setOption(option)
}

const updateGradeChart = () => {
  if (!gradeChart) return

  // 模拟年级数据
  const mockData = {
    '2021级': 150,
    '2022级': 180,
    '2023级': 200,
    '2024级': 220
  }

  const data = Object.entries(mockData).map(([name, value]) => ({
    name,
    value
  }))

  const option = {
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        name: '年级分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '30',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data
      }
    ]
  }

  gradeChart.setOption(option)
}

const updateGenderChart = () => {
  if (!genderChart) return

  // 模拟性别数据
  const maleCount = 420
  const femaleCount = 330

  const option = {
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        name: '性别分布',
        type: 'pie',
        radius: '50%',
        data: [
          { value: maleCount, name: '男生', itemStyle: { color: '#5470c6' } },
          { value: femaleCount, name: '女生', itemStyle: { color: '#ee6666' } }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  genderChart.setOption(option)
}

const updateStatusChart = () => {
  if (!statusChart) return

  // 模拟学籍状态数据
  const mockData = {
    'active': 650,
    'graduated': 100,
    'suspended': 5,
    'dropped': 2
  }

  const statusMap = {
    'active': '在校',
    'graduated': '已毕业',
    'suspended': '休学',
    'dropped': '退学'
  }

  const data = Object.entries(mockData).map(([key, value]) => ({
    name: statusMap[key as keyof typeof statusMap] || key,
    value
  }))

  const option = {
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        name: '学籍状态',
        type: 'pie',
        radius: '50%',
        data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  statusChart.setOption(option)
}

const updateEmploymentChart = () => {
  if (!employmentChart) return

  // 模拟就业状态数据
  const mockData = {
    'unemployed': 200,
    'employed': 450,
    'self_employed': 80,
    'further_study': 20
  }

  const employmentMap = {
    'unemployed': '未就业',
    'employed': '已就业',
    'self_employed': '自主创业',
    'further_study': '继续深造'
  }

  const data = Object.entries(mockData).map(([key, value]) => ({
    name: employmentMap[key as keyof typeof employmentMap] || key,
    value
  }))

  const option = {
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        name: '就业状态',
        type: 'pie',
        radius: '50%',
        data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  employmentChart.setOption(option)
}

const updateEnrollmentChart = () => {
  if (!enrollmentChart) return

  // 模拟入学趋势数据
  const mockData = [
    { date: '2024-01', count: 20 },
    { date: '2024-02', count: 15 },
    { date: '2024-03', count: 25 },
    { date: '2024-04', count: 30 },
    { date: '2024-05', count: 35 },
    { date: '2024-06', count: 40 },
    { date: '2024-07', count: 45 }
  ]

  const option = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: mockData.map(item => item.date)
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '入学人数',
        type: 'line',
        stack: 'Total',
        data: mockData.map(item => item.count),
        areaStyle: {},
        itemStyle: {
          color: '#91cc75'
        }
      }
    ]
  }

  enrollmentChart.setOption(option)
}

const refreshData = () => {
  fetchStatistics()
}

const exportReport = async () => {
  try {
    ElMessage.success('导出功能开发中')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 辅助方法
const getActiveStudents = () => {
  return (statistics as any).by_status?.['active'] || 650
}

const getGraduatedStudents = () => {
  return (statistics as any).by_status?.['graduated'] || 100
}

// 生命周期
onMounted(async () => {
  await nextTick()
  initCharts()
  fetchStatistics()
})
</script>

<style scoped>
.student-statistics {
  padding: 20px;
}

.page-card {
  min-height: calc(100vh - 120px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.header-actions {
  display: flex;
  gap: 12px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;

  .el-icon {
    font-size: 24px;
    color: white;
  }

  &.total {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }

  &.active {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  }

  &.graduated {
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  }

  &.employment {
    background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  }
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: var(--el-text-color-primary);
  line-height: 1;
  margin-bottom: 8px;
}

.stat-title {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  font-weight: 500;
}

.charts-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.chart-container {
  height: 320px;
  width: 100%;
}

.chart-container-large {
  height: 320px;
  width: 100%;
}

:deep(.el-card__header) {
  border-bottom: 1px solid var(--el-border-color-light);
  padding: 15px 20px;
}

:deep(.el-card__body) {
  padding: 20px;
}

@media (max-width: 768px) {
  .student-statistics {
    padding: 10px;
  }

  .stats-row .el-col {
    margin-bottom: 16px;
  }

  .chart-card {
    height: 300px;
  }

  .chart-container,
  .chart-container-large {
    height: 220px;
  }

  .stat-content {
    padding: 15px;
  }

  .stat-icon {
    width: 50px;
    height: 50px;
    margin-right: 12px;

    .el-icon {
      font-size: 20px;
    }
  }

  .stat-value {
    font-size: 24px;
  }
}
</style>